const Koa = require('koa')
const router = require('koa-router')()
const koaBody = require('koa-body')
const app = new Koa()
const TOKEN = '112233' // 模拟写死一个token

app.use(async(ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', ctx.header.origin)
    ctx.set('Access-Control-Request-Method', 'PUT, POST, DELETE, OPTIONS' )
    ctx.set(
        'Access-Control-Allow-With, Content-Type, Access','Origin', 'X-Request'
    )
    await next() 
})

app.use(async (ctx, next) => {
    if (ctx.path == '/api/login') {
        await next()
        return
    }
    // 不是登录接口，就需要验证token
    const cookies = ctx.cookies.get('token')
    if(cookies && cookies == TOKEN) {
        await next()
        return
    }
    ctx.body = {
        code: 401,
        msg: '权限错误'
    }
    return
})

app.use(koaBody({ multipart: true }))

router.get('api/corsname', async(ctx) => {
    ctx.body = {
        data: '曹哥'
    }
})

router.post('api/login', async(ctx) => {
    ctx.cookie.set('token', TOKEN, {
        expires: new Date(+ new Date() + 1000 * 60 * 24 * 7)
    })
    ctx.body = {
        msg: '登录成功',
        code: 0
    }
})

app.use(router.routes())
app.listen(3000, () => {
    console.log('服务已启动');
})